import scala.collection.mutable.ListBuffer

object ClassAndObjectDemo extends App {
  class Student(
                 val studentId: String,
                 var name: String,
                 private var _gender: String,
                 var age: Int,
                 var major: String
               ) {
    require(studentId.nonEmpty, "学号不能为空")
    require(name.nonEmpty, "姓名不能为空")
    require(_gender == "男" || _gender == "女", "性别必须是'男'或'女'")
    require(age > 0 && age < 120, "年龄必须在合理范围内")

    def this(studentId: String, name: String, gender: String) {
      this(studentId, name, gender, 18, "未确定")
    }

    def gender: String = _gender

    def setGender(newGender: String): Unit = {
      if (newGender == "男" || newGender == "女") {
        _gender = newGender
      } else {
        println("性别必须是'男'或'女'")
      }
    }

    def showInfo(): Unit = {
      println(s"学号：$studentId")
      println(s"姓名：$name")
      println(s"性别：$gender")
      println(s"年龄：$age")
      println(s"专业：$major")
    }

    override def toString: String =
      s"Student($studentId, $name, $gender, $age, $major)"
  }

  val student1 = new Student(studentId = "S2025001", name = "张三", _gender = "男", age = 20, major = "计算机科学")
  val student2 = new Student(studentId = "S2025002", name = "李四", gender = "女")

  println("=== 学生1信息 ===")
  student1.showInfo()

  println("\n=== 学生2信息（初始） ===")
  println(student2)

  student2.age = 19
  student2.major = "软件工程"
  student2.setGender("女")
  student2.setGender("保密")

  println("\n=== 学生2信息（修改后） ===")
  student2.showInfo()

  class Class(
               val classId: String,
               val className: String,
               private val students: ListBuffer[Student] = ListBuffer.empty
             ) {
    def addStudent(student: Student): Unit = {
      if (!students.exists(_.studentId == student.studentId)) {
        students += student
        println(s"学生 ${student.name} 已加入 $className")
      } else {
        println(s"学生 ${student.studentId} 已在班级中")
      }
    }

    def findStudent(studentId: String): Option[Student] = {
      students.find(_.studentId == studentId)
    }

    def studentCount: Int = students.size

    def showAllStudents(): Unit = {
      println(s"\n=== $className 学生列表（共 ${studentCount}人） ===")
      students.foreach(println)
    }
  }

  val csClass = new Class("CS2025", "计算机2025级")
  csClass.addStudent(student1)
  csClass.addStudent(student2)
  csClass.addStudent(student1)
  csClass.showAllStudents()

  val found = csClass.findStudent("S2025001")
  found match {
    case Some(student) => println(s"\n找到学生：${student.name}")
    case None => println("\n未找到该学生")
  }
}
//11.1110【动手练习1】：实现学生信息管理功能